package cn.com.yitong.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Meng Shen
 * @date 2022/5/6
 **/
@Component
public class CustomTenantInterceptor implements TenantLineHandler {

    @Override
    public Expression getTenantId() {
        //比如客户端请求将tenant_id 放在请求头中
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String tenantId = request.getHeader("tenant_id");
        if(StringUtils.isBlank(tenantId)){
            return new LongValue(1);
        }
        return new LongValue(Long.valueOf(tenantId));
    }

    @Override
    public boolean ignoreTable(String tableName) {
        return !"user".equalsIgnoreCase(tableName);
    }

}
